package com.guigusuqi.admin.config;

import com.alibaba.fastjson.JSON;
import com.guigusuqi.commonutils.constant.ResultCodeConstant;
import com.guigusuqi.commonutils.vo.Result;
import com.guigusuqi.user.entity.LoginUser;
import com.guigusuqi.user.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义一个过滤器，这个过滤器会去获取请求头中的token，对token进行解析取出其中的userId。
 * 使用userId去redis中获取对应的LoginUser对象。然后封装Authentication对象存入SecurityContextHolder
 *
 * 作用：只是为了校验token，如果token不存在是通过SecurityConfig.configure进行拦截的
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    @Resource
    @Lazy
    private SysUserService loginService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException
    {
        //  如果访问的是登录接口或者注册接口，并且携带了token就直接放行
        if(StringUtils.equals(request.getRequestURI(),"/user/login")
            || StringUtils.equals(request.getRequestURI(),"/user/loginBySelectUserName"))
        {
            filterChain.doFilter(request,response);
            return;
        }
        //  获取token
        String token = request.getHeader("Authorization");

        if(StringUtils.isEmpty(token))
        {
            filterChain.doFilter(request,response);
            return;
        }

        LoginUser loginUser = loginService.checkAndParseToken(token);

        if(Objects.isNull(loginUser))
        {
            Result result = Result.fail().code(ResultCodeConstant.NO_LOGIN.getCode()).message(ResultCodeConstant.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return;
        }

        //  封装Authentication对象存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, loginUser.getUser().getPassword(), loginUser.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //  放行
        filterChain.doFilter(request,response);
    }
}

